﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace SYH.Common.Utilities
{
    /// <summary>
    /// 公共的一些与 Lambda 表达式有关的工具
    /// </summary>
    public static class LambdaExpressionHelper
    {
        /// <summary>
        /// 根据泛型和泛型对应的属性名称，构建对应的表达式
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="propertyNmae">属性名，例如："SortCode"</param>
        /// <returns>类似 x => x.SortCode</returns>
        public static Expression<Func<T, object>> GetByPropertyName<T>(string propertyNmae)
        {
            Type type = typeof(T);
            var target = Expression.Parameter(typeof(object));
            var castTarget = Expression.Convert(target, type);
            var getPropertyValue = Expression.Property(castTarget, propertyNmae);
            return Expression.Lambda<Func<T, object>>(getPropertyValue, target);

        }

        /// <summary>
        /// linq去重
        /// </summary>
        public static IEnumerable<TSource> DistinctBy<TSource, TKey>
            (this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
        {
            HashSet<TKey> seenKeys = new HashSet<TKey>();
            foreach (TSource element in source)
            {
                if (seenKeys.Add(keySelector(element))) { yield return element; }
            }
        }
    }
}
